﻿using System;
using System.Collections.Generic;
using GeoAPI.Geometries;
using YJKGridTopologyCal.GeometriesGraph;

namespace YJKGridTopologyCal.Index.Chain
{
	public class MonotoneChainBuilder
	{
		private MonotoneChainBuilder()
		{
		}

		public static int[] ToIntArray(IList<int> list)
		{
			int[] array = new int[list.Count];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = list[i];
			}
			return array;
		}

		public static IList<MonotoneChain> GetChains(Coordinate[] pts)
		{
			return MonotoneChainBuilder.GetChains(pts, null);
		}

		public static IList<MonotoneChain> GetChains(Coordinate[] pts, object context)
		{
			List<MonotoneChain> list = new List<MonotoneChain>();
			int[] chainStartIndices = MonotoneChainBuilder.GetChainStartIndices(pts);
			for (int i = 0; i < chainStartIndices.Length - 1; i++)
			{
				MonotoneChain item = new MonotoneChain(pts, chainStartIndices[i], chainStartIndices[i + 1], context);
				list.Add(item);
			}
			return list;
		}

		public static int[] GetChainStartIndices(Coordinate[] pts)
		{
			int num = 0;
			List<int> list = new List<int>();
			list.Add(num);
			do
			{
				int num2 = MonotoneChainBuilder.FindChainEnd(pts, num);
				list.Add(num2);
				num = num2;
			}
			while (num < pts.Length - 1);
			return list.ToArray();
		}

		private static int FindChainEnd(Coordinate[] pts, int start)
		{
			int num = start;
			while (num < pts.Length - 1 && pts[num].Equals2D(pts[num + 1]))
			{
				num++;
			}
			if (num >= pts.Length - 1)
			{
				return pts.Length - 1;
			}
			int num2 = QuadrantOp.Quadrant(pts[num], pts[num + 1]);
			int num3 = start + 1;
			while (num3 < pts.Length && (pts[num3 - 1].Equals2D(pts[num3]) || QuadrantOp.Quadrant(pts[num3 - 1], pts[num3]) == num2))
			{
				num3++;
			}
			return num3 - 1;
		}
	}
}
